{% extends "base.html" %}

{% block title %}任务管理 - 数据预处理系统{% endblock %}

{% block content %}
<div class="row">
    <div class="col-12 mb-4">
        <div class="card border-0 shadow-sm">
            <div class="card-header bg-info text-white d-flex justify-content-between align-items-center">
                <h4 class="card-title mb-0">
                    <i class="fas fa-tasks me-2"></i>任务管理
                </h4>
                <button type="button" class="btn btn-light" onclick="refreshTasks()">
                    <i class="fas fa-sync-alt me-1"></i>刷新
                </button>
            </div>
            <div class="card-body">
                <div class="row mb-3">
                    <div class="col-md-3">
                        <div class="stat-card text-center p-3 border rounded">
                            <h3 class="text-primary mb-1" id="totalTasks">0</h3>
                            <small class="text-muted">总任务数</small>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="stat-card text-center p-3 border rounded">
                            <h3 class="text-warning mb-1" id="runningTasks">0</h3>
                            <small class="text-muted">运行中</small>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="stat-card text-center p-3 border rounded">
                            <h3 class="text-success mb-1" id="completedTasks">0</h3>
                            <small class="text-muted">已完成</small>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="stat-card text-center p-3 border rounded">
                            <h3 class="text-danger mb-1" id="failedTasks">0</h3>
                            <small class="text-muted">失败</small>
                        </div>
                    </div>
                </div>
                
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead>
                            <tr>
                                <th>任务ID</th>
                                <th>数据库</th>
                                <th>AI模型</th>
                                <th>状态</th>
                                <th>进度</th>
                                <th>开始时间</th>
                                <th>耗时</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="tasksList">
                            <!-- 任务列表将通过JavaScript动态加载 -->
                        </tbody>
                    </table>
                </div>
                
                <div id="emptyState" class="empty-state text-center py-5" style="display: none;">
                    <i class="fas fa-clipboard-list fa-3x text-muted mb-3"></i>
                    <h5>暂无任务记录</h5>
                    <p class="text-muted">
                        前往 <a href="{{ url_for('export_page') }}" class="text-decoration-none">数据导出</a> 页面创建新的导出任务
                    </p>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 任务详情模态框 -->
<div class="modal fade" id="taskDetailModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-info-circle me-2"></i>任务详情
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div id="taskDetailContent">
                    <!-- 任务详情内容 -->
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-success d-none" id="downloadTaskResult">
                    <i class="fas fa-download me-1"></i>下载结果
                </button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
let tasksData = [];
let refreshInterval;

$(document).ready(function() {
    loadTasks();
    
    // 自动刷新
    refreshInterval = setInterval(function() {
        loadTasks();
    }, 5000); // 每5秒刷新一次
});

function loadTasks() {
    $.get('/api/tasks')
        .done(function(data) {
            if (data.success) {
                tasksData = data.tasks;
                updateTasksTable();
                updateTasksStats();
            }
        })
        .fail(function() {
            console.error('加载任务列表失败');
        });
}

function updateTasksTable() {
    const tbody = $('#tasksList');
    tbody.empty();
    
    if (tasksData.length === 0) {
        $('#emptyState').show();
        return;
    } else {
        $('#emptyState').hide();
    }
    
    // 按开始时间倒序排列
    const sortedTasks = tasksData.sort((a, b) => new Date(b.start_time) - new Date(a.start_time));
    
    sortedTasks.forEach(task => {
        const statusClass = getStatusClass(task.status);
        const statusIcon = getStatusIcon(task.status);
        const statusText = getStatusText(task.status);
        
        const row = `
            <tr>
                <td>
                    <small class="font-monospace">${task.id.substring(0, 8)}...</small>
                </td>
                <td>${task.db_config || '-'}</td>
                <td>${task.ai_config || '未使用'}</td>
                <td>
                    <span class="badge bg-${statusClass}">
                        <i class="${statusIcon} me-1"></i>${statusText}
                    </span>
                </td>
                <td>
                    <div class="progress" style="height: 20px;">
                        <div class="progress-bar progress-bar-striped ${task.status === 'completed' ? '' : 'progress-bar-animated'}" 
                             role="progressbar" style="width: ${task.progress || 0}%">
                            ${task.progress || 0}%
                        </div>
                    </div>
                </td>
                <td>${formatDateTime(task.start_time)}</td>
                <td>${calculateDuration(task.start_time, task.update_time)}</td>
                <td>
                    <button class="btn btn-sm btn-outline-primary me-1" onclick="viewTaskDetail('${task.id}')">
                        <i class="fas fa-eye"></i>
                    </button>
                    ${task.status === 'completed' && task.result_file ? 
                        `<button class="btn btn-sm btn-outline-success" onclick="downloadTaskResult('${task.id}')">
                            <i class="fas fa-download"></i>
                        </button>` : ''
                    }
                </td>
            </tr>
        `;
        tbody.append(row);
    });
}

function updateTasksStats() {
    const total = tasksData.length;
    const running = tasksData.filter(t => ['starting', 'connecting', 'extracting', 'loading_ai', 'enhancing', 'exporting'].includes(t.status)).length;
    const completed = tasksData.filter(t => t.status === 'completed').length;
    const failed = tasksData.filter(t => t.status === 'failed').length;
    
    $('#totalTasks').text(total);
    $('#runningTasks').text(running);
    $('#completedTasks').text(completed);
    $('#failedTasks').text(failed);
}

function viewTaskDetail(taskId) {
    const task = tasksData.find(t => t.id === taskId);
    if (!task) return;
    
    const content = `
        <div class="row">
            <div class="col-md-6">
                <h6>基本信息</h6>
                <table class="table table-sm">
                    <tr><td>任务ID:</td><td class="font-monospace">${task.id}</td></tr>
                    <tr><td>数据库配置:</td><td>${task.db_config || '-'}</td></tr>
                    <tr><td>AI模型:</td><td>${task.ai_config || '未使用'}</td></tr>
                    <tr><td>状态:</td><td><span class="badge bg-${getStatusClass(task.status)}">${getStatusText(task.status)}</span></td></tr>
                    <tr><td>进度:</td><td>${task.progress || 0}%</td></tr>
                </table>
            </div>
            <div class="col-md-6">
                <h6>时间信息</h6>
                <table class="table table-sm">
                    <tr><td>开始时间:</td><td>${formatDateTime(task.start_time)}</td></tr>
                    <tr><td>更新时间:</td><td>${formatDateTime(task.update_time)}</td></tr>
                    <tr><td>耗时:</td><td>${calculateDuration(task.start_time, task.update_time)}</td></tr>
                </table>
            </div>
        </div>
        
        <div class="row mt-3">
            <div class="col-12">
                <h6>当前消息</h6>
                <div class="alert alert-info">
                    ${task.message || '无消息'}
                </div>
            </div>
        </div>
        
        ${task.error ? `
        <div class="row mt-3">
            <div class="col-12">
                <h6>错误信息</h6>
                <div class="alert alert-danger">
                    ${task.error}
                </div>
            </div>
        </div>
        ` : ''}
        
        ${task.options ? `
        <div class="row mt-3">
            <div class="col-12">
                <h6>导出选项</h6>
                <pre class="bg-light p-3 rounded"><code>${JSON.stringify(task.options, null, 2)}</code></pre>
            </div>
        </div>
        ` : ''}
    `;
    
    $('#taskDetailContent').html(content);
    
    // 显示/隐藏下载按钮
    if (task.status === 'completed' && task.result_file) {
        $('#downloadTaskResult').removeClass('d-none').off('click').on('click', function() {
            downloadTaskResult(task.id);
        });
    } else {
        $('#downloadTaskResult').addClass('d-none');
    }
    
    $('#taskDetailModal').modal('show');
}

function downloadTaskResult(taskId) {
    window.location.href = `/api/download/${taskId}`;
}

function refreshTasks() {
    loadTasks();
    Notification.success('任务列表已刷新');
}

function getStatusClass(status) {
    const map = {
        'starting': 'secondary',
        'connecting': 'info',
        'extracting': 'warning',
        'loading_ai': 'info',
        'enhancing': 'primary',
        'exporting': 'warning',
        'completed': 'success',
        'failed': 'danger'
    };
    return map[status] || 'secondary';
}

function getStatusIcon(status) {
    const map = {
        'starting': 'fas fa-play',
        'connecting': 'fas fa-link',
        'extracting': 'fas fa-database',
        'loading_ai': 'fas fa-robot',
        'enhancing': 'fas fa-magic',
        'exporting': 'fas fa-file-export',
        'completed': 'fas fa-check',
        'failed': 'fas fa-times'
    };
    return map[status] || 'fas fa-question';
}

function getStatusText(status) {
    const map = {
        'starting': '启动中',
        'connecting': '连接中',
        'extracting': '提取中',
        'loading_ai': '加载AI',
        'enhancing': '增强中',
        'exporting': '导出中',
        'completed': '已完成',
        'failed': '失败'
    };
    return map[status] || '未知';
}

function formatDateTime(dateStr) {
    if (!dateStr) return '-';
    return new Date(dateStr).toLocaleString('zh-CN');
}

function calculateDuration(startTime, endTime) {
    if (!startTime) return '-';
    
    const start = new Date(startTime);
    const end = endTime ? new Date(endTime) : new Date();
    const duration = Math.floor((end - start) / 1000);
    
    return Utils.formatDuration(duration);
}

// 页面卸载时清理定时器
$(window).on('beforeunload', function() {
    if (refreshInterval) {
        clearInterval(refreshInterval);
    }
});
</script>
{% endblock %}